﻿using Dapper;
using Entity.Utils;
using EntityLibrary.Business.RegistProcess.Entity;
using EntityLibrary.Business.RegistProcess.Sql;
using EntityLibrary.DomainCheck;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;

namespace EntityLibrary.Business.RegistProcess
{
    public class RegistProcessService
    {
        string connStr = Decryption.StrDecrypt(ConfigurationManager.ConnectionStrings["HISDATA"].ConnectionString);

        //查询当天有号的一级科室
        [Obsolete]
        public bool GetFirstDept4Live(int CallNo, string CallName, string firstDeptCode, out IList<FirstDept> firstDepts)
        {
            if (default(KeyValuePair<string, string>).Equals(
                CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
                ))
            {
                throw new InvalidOperationException("非法访问失败，请联系接口开发商！");
            }


            var conn = new SqlConnection(connStr);
            conn.Open();

            string sqlStr = SQLFileHelper.GetSql("GetFirstDept4Live.sql");

            var sqlParam = new DynamicParameters();
            if (string.IsNullOrWhiteSpace(firstDeptCode))
                firstDeptCode = "%";
            sqlParam.Add("@FirstDeptCode_In", firstDeptCode);

            firstDepts = conn.Query<FirstDept>(sqlStr, sqlParam).ToList();
            conn.Close();
            return true;
        }
        //查询当天有号的二级科室
        public bool GetSecondDept4Live(int CallNo, string CallName, string secondDeptCode, out IList<SecondDept> secondDepts)
        {
            if (default(KeyValuePair<string, string>).Equals(
                CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
                ))
            {
                throw new InvalidOperationException("非法访问失败，请联系接口开发商！");
            }


            var conn = new SqlConnection(connStr);
            conn.Open();

            string sqlStr = SQLFileHelper.GetSql("GetSecondDept4Live.sql");

            var sqlParam = new DynamicParameters();
            if (string.IsNullOrWhiteSpace(secondDeptCode))
                secondDeptCode = "%";
            sqlParam.Add("@SecondDeptCode_In", secondDeptCode);

            secondDepts = conn.Query<SecondDept>(sqlStr, sqlParam).ToList();
            conn.Close();
            return true;
        }
        //查询当天的医生
        public bool GetDoct4Live(int CallNo, string CallName, string secondDeptCode, string doctCode, bool hideEmptyDoct, out IList<Doct> docts)
        {
            if (default(KeyValuePair<string, string>).Equals(
                CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
                ))
            {
                throw new InvalidOperationException("非法访问失败，请联系接口开发商！");
            }


            var conn = new SqlConnection(connStr);
            conn.Open();

            string sqlStr = SQLFileHelper.GetSql("GetDoct4Live.sql");

            var sqlParam = new DynamicParameters();
            if (string.IsNullOrWhiteSpace(doctCode))
                doctCode = "%";
            sqlParam.Add("@SecondDeptCode_In", secondDeptCode);
            sqlParam.Add("@DoctCode_In", doctCode);
            sqlParam.Add("@HideEmptyDoct_In", hideEmptyDoct);

            docts = conn.Query<Doct>(sqlStr, sqlParam).ToList();
            conn.Close();
            return true;
        }
        //预挂号
        public bool PrepareRegister(int CallNo, string CallName, string deptId, string doctId, string patientId
            , ref int registerId, ref string deptName, ref string address, ref string doctorName, ref string currentNumber, ref string queueNumber
            , ref decimal originAmount, ref decimal totalAmount, ref string errorMessage)
        {
            if (default(KeyValuePair<string, string>).Equals(
                CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
                ))
            {
                errorMessage = "非法访问失败，请联系接口开发商！";
                return false;
            }


            var conn = new SqlConnection(connStr);
            string sqlStr = SQLFileHelper.GetSql("PrepareRegister.sql");
            conn.Open();
            try
            {
                DataSet ds = new DataSet();
                SqlCommand sc = new SqlCommand(sqlStr, conn);
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@CallNo_In", Value = CallNo });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@CallName_In", Value = CallName });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@PatientId_In", Value = patientId });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@DeptCode_In", Value = deptId });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@DoctCode_In", Value = doctId });
                SqlDataReader sdr = sc.ExecuteReader();

                if (!sdr.HasRows) throw new InvalidOperationException("程序出错，请联系开发商！");
                sdr.Read();
                if ((int)sdr["Result"] != 1)
                {
                    errorMessage = (string)sdr["ResultText"];
                    return false;
                }
                registerId = (int)sdr["registerId"];
                deptName = (string)sdr["deptName"];
                address = (string)sdr["address"];
                doctorName = (string)sdr["doctName"];
                currentNumber = (string)sdr["currentNumber"];
                queueNumber = (string)sdr["queueNumber"];
                originAmount = (decimal)sdr["originAmount"];
                totalAmount = (decimal)sdr["totalAmount"];
                return true;
            }
            finally
            {
                conn.Close();
            }
        }
        //当日挂号退号
        public bool RefundRegist(int CallNo, string CallName, string registerId, ref string errorMessage)
        {

            if (default(KeyValuePair<string, string>).Equals(
                CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
                ))
            {
                errorMessage = "非法访问失败，请联系接口开发商！";
                return false;
            }


            var conn = new SqlConnection(connStr);
            conn.Open();

            string sqlStr = SQLFileHelper.GetSql("RefundRegist.sql");
            try
            {
                DataSet ds = new DataSet();
                SqlCommand sc = new SqlCommand(sqlStr, conn);
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@RegistId_In", Value = registerId });
                SqlDataReader sdr = sc.ExecuteReader();

                if (!sdr.HasRows) throw new InvalidOperationException("程序出错，请联系开发商！");
                sdr.Read();
                if ((int)sdr["Result"] != 1)
                {
                    errorMessage = (string)sdr["ResultText"];
                    return false;
                }
                return true;
            }
            finally
            {
                conn.Close();
            }
        }
        //确认挂号
        public bool RegistToday(int CallNo, string CallName, int registerId
                              , string patientId, string orderNumber, PayType payType
                              , string payNumber, string isMedicarePay, string medicareNumber
                              , decimal payAmount, decimal medicareAmount, decimal totalAmount
                              , string extend, string terminalId
                              , ref string errorMessage, ref string sourceNumber, ref string transFlow
                              , ref DateTime? transactionTime, ref string currentNumber, ref string queueNumber
                              , ref string clinicRange, ref string name
                              , ref Sex sex, ref string deptName, ref string address
                              , ref string doctorName, ref string duty, ref Dictionary<string, decimal> orders
                              )
        {
            if (default(KeyValuePair<string, string>).Equals(
                            CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
                            ))
            {
                errorMessage = "非法访问失败，请联系接口开发商！";
                return false;
            }



            var conn = new SqlConnection(connStr);
            string sqlStr = Regex.Replace(SQLFileHelper.GetSql("RegistToday.sql"), @" +", " ");
            conn.Open();
            try
            {
                DataSet ds = new DataSet();
                SqlTransaction st = conn.BeginTransaction();
                SqlCommand sc = new SqlCommand(sqlStr, conn, st);

                sc.Parameters.Add(new SqlParameter() { ParameterName = "@CallNo_In", Value = CallNo });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@CallName_In", Value = CallName });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@RegistId_In", Value = registerId });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@PayMoney_In", Value = totalAmount });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@PatientId_In", Value = patientId });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@TransNo_In", Value = orderNumber });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@PayWay_In", Value = payType });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@BanktransNo_In", Value = payNumber });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@PayDeviceId_In", Value = terminalId });
                switch (payType)
                {
                    case PayType.就诊卡下卡: sc.Parameters.Add(new SqlParameter() { ParameterName = "@YBFlag_In", Value = 6 }); break;
                    case PayType.现金: sc.Parameters.Add(new SqlParameter() { ParameterName = "@YBFlag_In", Value = 0 }); break;
                    case PayType.银联下卡: sc.Parameters.Add(new SqlParameter() { ParameterName = "@YBFlag_In", Value = 4 }); break;
                    default: sc.Parameters.Add(new SqlParameter() { ParameterName = "@YBFlag_In", Value = 9 }); break;
                }

                //sc.Parameters.Add(new SqlParameter() { ParameterName = "@IsMedicarePay_In", Value = isMedicarePay });
                //sc.Parameters.Add(new SqlParameter() { ParameterName = "@MedicareNumber_In", Value = medicareNumber });
                //sc.Parameters.Add(new SqlParameter() { ParameterName = "@Extend_In", Value = extend });
                DataTable sdr = new DataTable();
                try
                {
                    SqlDataAdapter sda = new SqlDataAdapter(sc);
                    sda.Fill(sdr);
                    st.Commit();
                }
                catch (Exception e)
                {
                    st.Rollback();
                    throw new InvalidOperationException(e.Message);
                }

                if (sdr.Rows.Count <= 0) throw new InvalidOperationException("程序出错，请联系开发商！");
                var i = 0;
                foreach (DataRow row in sdr.Rows)
                {
                    if ((Convert.IsDBNull(row["Result"]) ? 0 : (int)row["Result"]) != 1)
                    {
                        errorMessage = Convert.IsDBNull(row["ResultText"]) ? string.Empty : (string)row["ResultText"];
                        return false;
                    }
                    if (i == 0)
                    {
                        sourceNumber = Convert.IsDBNull(row["sourceNumber"]) ? string.Empty : (string)row["sourceNumber"];
                        transFlow = Convert.IsDBNull(row["transFlow"]) ? string.Empty : (string)row["transFlow"];
                        transactionTime = Convert.IsDBNull(row["transactionTime"]) ? null : (DateTime?)row["transactionTime"];
                        currentNumber = Convert.IsDBNull(row["currentNumber"]) ? string.Empty : (string)row["currentNumber"];
                        queueNumber = Convert.IsDBNull(row["queueNumber"]) ? string.Empty : (string)row["queueNumber"];
                        clinicRange = Convert.IsDBNull(row["clinicRange"]) ? string.Empty : (string)row["clinicRange"];
                        name = Convert.IsDBNull(row["name"]) ? string.Empty : (string)row["name"];
                        sex = (Sex)Enum.Parse(typeof(Sex), Convert.ToString(row["sex"]));
                        deptName = Convert.IsDBNull(row["deptName"]) ? string.Empty : (string)row["deptName"];
                        address = Convert.IsDBNull(row["address"]) ? string.Empty : (string)row["address"];
                        doctorName = Convert.IsDBNull(row["doctorName"]) ? string.Empty : (string)row["doctorName"];
                        duty = Convert.IsDBNull(row["duty"]) ? string.Empty : (string)row["duty"];
                    }
                    orders.Add(
                        Convert.IsDBNull(row["CheckName"]) ? string.Empty : (string)row["CheckName"],
                        Convert.IsDBNull(row["CheckPrice"]) ? 0 : (decimal)row["CheckPrice"]
                        );
                    i++;
                }
                return true;
            }
            finally
            {
                conn.Close();
            }

        }

        //查询可预约一级科室
        [Obsolete]
        public bool GetFirstDept4Reservation(int CallNo, string CallName, string firstDeptCode, DateTime reservationDate, out IList<FirstDept> firstDepts)
        {
            if (default(KeyValuePair<string, string>).Equals(
             CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
             ))
            {
                throw new InvalidOperationException("非法访问失败，请联系接口开发商！");
            }

            var conn = new SqlConnection(connStr);
            conn.Open();

            string sqlStr = SQLFileHelper.GetSql("GetFirstDept4Reservation.sql");

            var sqlParam = new DynamicParameters();
            if (string.IsNullOrWhiteSpace(firstDeptCode))
                firstDeptCode = "%";
            sqlParam.Add("@FirstDeptCode_In", firstDeptCode);
            sqlParam.Add("@ReservationDate_In", reservationDate);

            firstDepts = conn.Query<FirstDept>(sqlStr, sqlParam).ToList();
            conn.Close();
            return true;
        }
        //查询可预约二级科室
        public bool GetSecondDept4Reservation(int CallNo, string CallName, string secondDeptCode, DateTime reservationDate, out IList<SecondDept> secondDepts)
        {
            if (default(KeyValuePair<string, string>).Equals(
             CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
             ))
            {
                throw new InvalidOperationException("非法访问失败，请联系接口开发商！");
            }

            var conn = new SqlConnection(connStr);
            conn.Open();

            string sqlStr = SQLFileHelper.GetSql("GetSecondDept4Reservation.sql");

            var sqlParam = new DynamicParameters();
            if (string.IsNullOrWhiteSpace(secondDeptCode))
                secondDeptCode = "%";
            sqlParam.Add("@SecondDeptCode_In", secondDeptCode);
            sqlParam.Add("@ReservationDate_In", reservationDate);

            secondDepts = conn.Query<SecondDept>(sqlStr, sqlParam).ToList();
            conn.Close();
            return true;
        }
        //查询可预约的医生
        public bool GetDoct4Reservation(int CallNo, string CallName, string secondDeptCode, string doctCode, DateTime reservationDate, bool hideEmptyDoct, out IList<Doct> docts)
        {
            if (default(KeyValuePair<string, string>).Equals(
             CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
             ))
            {
                throw new InvalidOperationException("非法访问失败，请联系接口开发商！");
            }

            var conn = new SqlConnection(connStr);
            conn.Open();

            string sqlStr = SQLFileHelper.GetSql("GetDoct4Reservation.sql");

            var sqlParam = new DynamicParameters();
            if (string.IsNullOrWhiteSpace(doctCode))
                doctCode = "%";
            sqlParam.Add("@DeptCode_In", secondDeptCode);
            sqlParam.Add("@DoctCode_In", doctCode);
            sqlParam.Add("@HideEmptyDoct_In", hideEmptyDoct);
            sqlParam.Add("@ReservationDate_In", reservationDate);

            docts = conn.Query<Doct>(sqlStr, sqlParam).ToList();
            conn.Close();
            return true;
        }
        //预约医生时间段
        public List<TimeInterval> GetReservationTidByDoctor(int CallNo, string CallName, DateTime reservationDate, string deptId, string doctorId)
        {
            if (default(KeyValuePair<string, string>).Equals(
                CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
                ))
            {
                throw new InvalidOperationException("非法访问失败，请联系接口开发商！");
            }


            var conn = new SqlConnection(connStr);
            string sqlStr = SQLFileHelper.GetSql("GetReservationTidByDoctor.sql");
            var sqlParam = new DynamicParameters();
            sqlParam.Add("@ReservationDate_In", reservationDate);
            sqlParam.Add("@DeptCode_In", deptId);
            sqlParam.Add("@DoctCode_In", doctorId);

            var timeIntervalList = conn.Query<TimeInterval>(sqlStr, sqlParam).ToList();
            conn.Close();
            return timeIntervalList;
        }
        //预约科室时间段
        public List<TimeInterval> GetReservationTidByDepartment(int CallNo, string CallName, DateTime reservationDate, string deptId)
        {
            if (default(KeyValuePair<string, string>).Equals(
               CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
               ))
            {
                throw new InvalidOperationException("非法访问失败，请联系接口开发商！");
            }


            var conn = new SqlConnection(connStr);
            string sqlStr = SQLFileHelper.GetSql("GetReservationTidByDepartment.sql");
            var sqlParam = new DynamicParameters();
            sqlParam.Add("@ReservationDate_In", reservationDate);
            sqlParam.Add("@DeptCode_In", deptId);

            var timeIntervalList = conn.Query<TimeInterval>(sqlStr, sqlParam).ToList();
            conn.Close();
            return timeIntervalList;
        }
        //预约挂号占号（预挂号）
        public Dictionary<string, object> PrepareReservationRegist(int CallNo, string CallName, DateTime reservationtDate, string clinicRangeId, string deptId, string doctId, string patientId)
        {
            if (default(KeyValuePair<string, string>).Equals(
               CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
               ))
            {
                throw new InvalidOperationException("非法访问失败，请联系接口开发商！");
            }


            var conn = new SqlConnection(connStr);
            string sqlStr = SQLFileHelper.GetSql("PrepareReservationRegist.sql");
            conn.Open();
            try
            {
                DataSet ds = new DataSet();
                SqlCommand sc = new SqlCommand(sqlStr, conn);
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@CallNo_In", Value = CallNo });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@CallName_In", Value = CallName });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@PatientId_In", Value = patientId });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@DeptCode_In", Value = deptId });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@DoctCode_In", Value = doctId });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@ReservationDate_In", Value = reservationtDate });
                //sc.Parameters.Add(new SqlParameter() { ParameterName = "@Timeinterval_In", Value = clinicRangeId });
                SqlDataReader sdr = sc.ExecuteReader();

                if (!sdr.HasRows) throw new InvalidOperationException("程序出错，请联系开发商！");
                sdr.Read();
                if ((int)sdr["Result"] != 1)
                {
                    throw new InvalidOperationException((string)sdr["ResultText"]);
                }
                Dictionary<string, object> result = new Dictionary<string, object>();
                result.Add("registerId", Convert.ToInt32(sdr["RegisterId"]));
                result.Add("deptName", (string)sdr["DeptName"]);
                result.Add("address", (string)sdr["Address"]);
                result.Add("doctorName", (string)sdr["DoctName"]);
                result.Add("currentNumber", (string)sdr["CurrentNumber"]);
                result.Add("queueNumber", (string)sdr["QueueNumber"]);
                result.Add("clinicRange", (string)sdr["TimeInterval"]);
                result.Add("originAmount", (decimal)sdr["OriginAmount"]);
                result.Add("totalAmount", (decimal)sdr["TotalAmount"]);
                return result;
            }
            finally
            {
                conn.Close();
            }
        }
        //预约挂号退号
        public bool RefundReservationRegist(int CallNo, string CallName, string registerId, ref string errorMessage)
        {
            if (default(KeyValuePair<string, string>).Equals(
                CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
                ))
            {
                errorMessage = "非法访问失败，请联系接口开发商！";
                return false;
            }



            var conn = new SqlConnection(connStr);
            conn.Open();

            string sqlStr = SQLFileHelper.GetSql("RefundReservationRegist.sql");
            try
            {
                DataSet ds = new DataSet();
                SqlCommand sc = new SqlCommand(sqlStr, conn);
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@RegistId_In", Value = registerId });
                SqlDataReader sdr = sc.ExecuteReader();

                if (!sdr.HasRows) throw new InvalidOperationException("程序出错，请联系开发商！");
                sdr.Read();
                if ((int)sdr["Result"] != 1)
                {
                    errorMessage = (string)sdr["ResultText"];
                    return false;
                }
                return true;
            }
            finally
            {
                conn.Close();
            }
        }
        //预约挂号确认
        public bool ReservationRegist(int CallNo, string CallName, int registerId
                              , string patientId, string orderNumber, PayType payType
                              , string payNumber, string isMedicarePay, string medicareNumber
                              , decimal payAmount, decimal medicareAmount, decimal totalAmount
                              , string extend, string terminalId
                              , ref string errorMessage, ref DateTime? appointDate, ref string sourceNumber
                              , ref string transFlow, ref string transactionTime, ref string currentNumber
                              , ref string queueNumber, ref string clinicRange, ref string name
                              , ref Sex sex, ref string deptName, ref string address
                              , ref string doctorName, ref string duty, ref Dictionary<string, decimal> orders)

        {
            if (default(KeyValuePair<string, string>).Equals(
                            CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
                            ))
            {
                errorMessage = "非法访问失败，请联系接口开发商！";
                return false;
            }

            var conn = new SqlConnection(connStr);
            string sqlStr = Regex.Replace(SQLFileHelper.GetSql("ReservationRegist.sql"), @" +", " ");
            conn.Open();
            try
            {
                DataSet ds = new DataSet();
                SqlTransaction st = conn.BeginTransaction();
                SqlCommand sc = new SqlCommand(sqlStr, conn, st);

                sc.Parameters.Add(new SqlParameter() { ParameterName = "@CallNo_In", Value = CallNo });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@CallName_In", Value = CallName });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@RegistId_In", Value = registerId });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@PayMoney_In", Value = payAmount });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@PatientId_In", Value = patientId });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@TransNo_In", Value = orderNumber });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@PayWay_In", Value = payType });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@BanktransNo_In", Value = payNumber });
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@PayDeviceId_In", Value = terminalId });

                switch (payType)
                {
                    case PayType.就诊卡下卡: sc.Parameters.Add(new SqlParameter() { ParameterName = "@YBFlag_In", Value = 6 }); break;
                    case PayType.现金: sc.Parameters.Add(new SqlParameter() { ParameterName = "@YBFlag_In", Value = 0 }); break;
                    case PayType.银联下卡: sc.Parameters.Add(new SqlParameter() { ParameterName = "@YBFlag_In", Value = 4 }); break;
                    default: sc.Parameters.Add(new SqlParameter() { ParameterName = "@YBFlag_In", Value = 9 }); break;
                }

                DataTable sdr = new DataTable();
                try
                {
                    SqlDataAdapter sda = new SqlDataAdapter(sc);
                    sda.Fill(sdr);
                    st.Commit();
                }
                catch (Exception e)
                {
                    st.Rollback();
                    throw new InvalidOperationException(e.Message);
                }

                if (sdr.Rows.Count <= 0) throw new InvalidOperationException("程序出错，请联系开发商！");
                var i = 0;
                foreach (DataRow row in sdr.Rows)
                {
                    if ((Convert.IsDBNull(row["Result"]) ? 0 : (int)row["Result"]) != 1)
                    {
                        errorMessage = Convert.IsDBNull(row["ResultText"]) ? string.Empty : (string)row["ResultText"];
                        return false;
                    }
                    if (i == 0)
                    {
                        appointDate = Convert.IsDBNull(row["appointDate"]) ? null : (DateTime?)row["appointDate"];
                        sourceNumber = Convert.IsDBNull(row["sourceNumber"]) ? string.Empty : (string)row["sourceNumber"];
                        transFlow = Convert.IsDBNull(row["transFlow"]) ? string.Empty : (string)row["transFlow"];
                        transactionTime = Convert.IsDBNull(row["transactionTime"]) ? null : row["transactionTime"].ToString();
                        currentNumber = Convert.IsDBNull(row["currentNumber"]) ? string.Empty : (string)row["currentNumber"];
                        queueNumber = Convert.IsDBNull(row["queueNumber"]) ? string.Empty : (string)row["queueNumber"];
                        clinicRange = Convert.IsDBNull(row["clinicRange"]) ? string.Empty : (string)row["clinicRange"];
                        name = Convert.IsDBNull(row["name"]) ? string.Empty : (string)row["name"];
                        sex = (Sex)Enum.Parse(typeof(Sex), Convert.ToString(row["sex"]));
                        deptName = Convert.IsDBNull(row["deptName"]) ? string.Empty : (string)row["deptName"];
                        address = Convert.IsDBNull(row["address"]) ? string.Empty : (string)row["address"];
                        doctorName = Convert.IsDBNull(row["doctorName"]) ? string.Empty : (string)row["doctorName"];
                        duty = Convert.IsDBNull(row["duty"]) ? string.Empty : (string)row["duty"];
                    }
                    //预约挂号这里没到看病当天his是不记录费用的
                    orders.Add(
                        Convert.IsDBNull(row["CheckName"]) ? string.Empty : (string)row["CheckName"],
                        Convert.IsDBNull(row["CheckPrice"]) ? 0 : (decimal)row["CheckPrice"]
                        );
                    i++;
                }
                return true;
            }
            finally
            {
                conn.Close();
            }
        }
        //预约取号列表
        public List<Dictionary<string, string>> GetReservationList(int CallNo, string CallName, string patientId)
        {
            if (default(KeyValuePair<string, string>).Equals(
              CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
              ))
            {
                throw new InvalidOperationException("非法访问失败，请联系接口开发商！");
            }



            var conn = new SqlConnection(connStr);
            string sqlStr = SQLFileHelper.GetSql("GetReservationList.sql");

            conn.Open();
            try
            {
                DataSet ds = new DataSet();
                SqlCommand sc = new SqlCommand(sqlStr, conn);
                sc.Parameters.Add(new SqlParameter() { ParameterName = "@PatientId_In", Value = patientId });

                SqlDataReader sdr = sc.ExecuteReader();

                if (sdr.HasRows)
                {
                    List<Dictionary<string, string>> dicAppointment = new List<Dictionary<string, string>>();
                    while (sdr.Read())
                    {
                        Dictionary<string, string> appointment = new Dictionary<string, string>();
                        appointment.Add("registerId", sdr["registerId"].ToString());
                        appointment.Add("deptName", sdr["deptName"].ToString());
                        appointment.Add("regTime", sdr["regTime"].ToString());
                        appointment.Add("price", sdr["price"].ToString());
                        appointment.Add("registerStatus", sdr["registerStatus"].ToString());
                        dicAppointment.Add(appointment);
                    }
                    return dicAppointment;
                }
                else
                {
                    throw new InvalidOperationException("程序出错，请联系开发商！");
                }
            }
            finally
            {
                conn.Close();
            }
        }

        //预约挂号取号
        public Dictionary<string, object> GetReservationInfo(int CallNo, string CallName, string registId)
        {
            if (default(KeyValuePair<string, string>).Equals(
             CallNoType.CallNos.FirstOrDefault(c => c.Key.Equals(CallNo) && c.Value.Equals(CallName))
             ))
            {
                throw new InvalidOperationException("非法访问失败，请联系接口开发商！");
            }

            var conn = new SqlConnection(connStr);
            string sqlStr = SQLFileHelper.GetSql("GetReservationInfo.sql");

            conn.Open();

            DataSet ds = new DataSet();
            SqlTransaction st = conn.BeginTransaction();
            SqlCommand sc = new SqlCommand(sqlStr, conn, st);

            sc.Parameters.Add(new SqlParameter() { ParameterName = "@RegistId_In", Value = registId });

            DataTable sdr = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(sc);
            sda.Fill(sdr);
            if (sdr.Rows.Count <= 0) throw new InvalidOperationException("程序出错，请联系开发商！");
            var i = 0;
            Dictionary<string, object> result = new Dictionary<string, object>();
            Dictionary<string, object> orders = new Dictionary<string, object>();
            foreach (DataRow row in sdr.Rows)
            {
                if (i == 0)
                {
                    result.Add("appointDate", Convert.IsDBNull(row["sourceNumber"]) ? null : (DateTime?)row["sourceNumber"]);
                    result.Add("sourceNumber", Convert.IsDBNull(row["sourceNumber"]) ? string.Empty : (string)row["sourceNumber"]);
                    result.Add("transFlow", Convert.IsDBNull(row["transFlow"]) ? string.Empty : (string)row["transFlow"]);
                    result.Add("transactionTime", Convert.IsDBNull(row["transactionTime"]) ? null : (DateTime?)row["transactionTime"]);
                    result.Add("currentNumber", Convert.IsDBNull(row["currentNumber"]) ? string.Empty : (string)row["currentNumber"]);
                    result.Add("queueNumber", Convert.IsDBNull(row["queueNumber"]) ? string.Empty : (string)row["queueNumber"]);
                    result.Add("clinicRange", Convert.IsDBNull(row["clinicRange"]) ? string.Empty : (string)row["clinicRange"]);
                    result.Add("name", Convert.IsDBNull(row["name"]) ? string.Empty : (string)row["name"]);
                    result.Add("sex", (Sex)Enum.Parse(typeof(Sex), Convert.ToString(row["sex"])));
                    result.Add("deptName", Convert.IsDBNull(row["deptName"]) ? string.Empty : (string)row["deptName"]);
                    result.Add("address", Convert.IsDBNull(row["address"]) ? string.Empty : (string)row["address"]);
                    result.Add("doctorName", Convert.IsDBNull(row["doctorName"]) ? string.Empty : (string)row["doctorName"]);
                    result.Add("duty", Convert.IsDBNull(row["duty"]) ? string.Empty : (string)row["duty"]);
                }
                //预约挂号这里没到看病当天his是不记录费用的
                orders.Add(
                    Convert.IsDBNull(row["CheckName"]) ? string.Empty : (string)row["CheckName"],
                    Convert.IsDBNull(row["CheckPrice"]) ? 0 : (decimal)row["CheckPrice"]
                    );
                result.Add("oders", orders);
                i++;
            }
            return result;
        }
    }
}
